<template>
    <page-meta :page-style="$theme.pageStyle">
        <!-- #ifndef H5 -->
        <navigation-bar :front-color="$theme.navColor" :background-color="$theme.navBgColor" />
        <!-- #endif -->
    </page-meta>
    <view class="h-full goods-order" :style="$theme.pageStyle">
        <!-- Header -->
        <navigator url="/packageA/pages/user_address/user_address?type=true" hover-class="none">
            <address-card>
                <template v-if="!orderInfo?.address?.contact">
                    <view class="text-[#101010] text-lg"> 设置收货地址 </view>
                </template>
                <template v-else>
                    <view class="text-lg text-[#222] mb-[14rpx]">
                        <text class="font-medium">{{ orderInfo?.address.contact }}</text>
                        <text class="ml-[10rpx]">{{ orderInfo?.address.mobile }}</text>
                    </view>
                    <view class="text-base text-content">
                        {{ orderInfo?.address.addressDetail }}
                    </view>
                </template>
            </address-card>
        </navigator>

        <!-- Main -->
        <view class="m-[20rpx] rounded-[14rpx] bg-white overflow-hidden">
            <goods-card
                shape="rectangle"
                :image="item.image"
                :imageStyle="{ width: '170rpx', height: '170rpx' }"
                :name="item.goodsName"
                :containStyle="{ height: '220rpx', 'border-radius': '0' }"
                v-for="item in orderInfo.goods"
                :key="item.id"
            >
                <view class="text-muted mt-[6rpx]">
                    {{ item.skuValueArr }}
                </view>
                <view class="flex justify-between mt-[8rpx]">
                    <!-- 普通商品价格 -->
                    <price
                        v-if="GoodsTypeEnum.ORDINARY == orderInfo.orderType"
                        :content="item.price"
                        main-size="32rpx"
                        minor-size="24rpx"
                    />
                    <!-- 秒杀商品价格 -->
                    <price
                        v-if="GoodsTypeEnum.SECKILL == orderInfo.orderType"
                        :content="item.price"
                        main-size="32rpx"
                        minor-size="24rpx"
                        prefix="秒杀价￥"
                    />

                    <text class="text-content"> x {{ item.num }} </text>
                </view>
            </goods-card>
            <!--  配送方式 -->
            <view class="p-[24rpx] flex justify-between">
                <text class="text-[#333333] text-base">配送方式</text>
                <text class="text-[#101010] text-base">
                    {{ orderInfo.deliveryTypeDesc }}
                </text>
            </view>
            <!--  备注 -->
            <view class="p-[24rpx] flex w-full col-start">
                <text class="text-[#333333] mt-[6rpx] text-base">买家备注</text>
                <view class="flex-1 ml-2">
                    <u-input
                        v-model="orderParam.remark"
                        type="textarea"
                        placeholder="请输入备注"
                        height="80"
                    />
                </view>
            </view>
        </view>

        <view class="m-[20rpx] rounded-[14rpx] overflow-hidden bg-white">
            <view class="p-[24rpx] flex justify-between">
                <text class="text-[#333333] text-base">商品总额</text>
                <text class="text-[#101010] text-base">¥{{ orderInfo.goodsAmount }}</text>
            </view>
            <view class="p-[24rpx] flex justify-between">
                <text class="text-[#333333] text-base">运费</text>
                <text class="text-base text-[#101010]">¥{{ orderInfo.freightAmount }}</text>
            </view>

            <!-- 优惠券 -->
            <coupon-popup
                v-if="GoodsTypeEnum.ORDINARY == orderInfo.orderType"
                v-model:orderParam="orderParam"
                :couponAmount="orderInfo.couponAmount"
                @refresh="getOrderDetail"
            ></coupon-popup>
        </view>

        <!-- Footer -->
        <view class="flex items-center justify-end bg-white submit">
            <view class="mr-[30rpx]">
                <text class="text-lg">合计:</text>
                <price :content="orderInfo.orderAmount" mainSize="38rpx" minorSize="30rpx" />
            </view>
            <button class="submit-btn" @tap="onSubmitOrder">提交订单</button>
        </view>

        <!-- Component 页面状态 -->
        <page-status ref="pageRef"></page-status>

        <!-- Component 支付 -->
        <payment
            v-if="payState.showPay || payState.showCheck"
            v-model:show="payState.showPay"
            v-model:show-check="payState.showCheck"
            :order-id="payState.orderId"
            :from="payState.from"
            :redirect="payState.redirect"
            @success="handlePayResult"
            @fail="handlePayResult"
        />
    </view>
</template>

<script lang="ts" setup>
import { reactive, shallowRef, unref, nextTick, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { orderSettle, orderSubmit } from '@/api/order'
import GoodsAbnormalImage from '@/static/images/empty/goods.png'
import { useAddress } from '@/hooks/useAddress'
import { PayFromType } from '@/enums/appEnums'
import { useLockFn } from '@/hooks/useLockFn'
import { GoodsTypeEnum } from '@/enums/goodsEnums'
import { useRouter } from 'uniapp-router-next'
import { queryToArrObj } from '@/utils/util'

import CouponPopup from '@/pages/goods_order/compound/coupon-popup.vue'

const router = useRouter()
const { address } = useAddress()
const pageRef = shallowRef()
const payState = reactive({
    orderId: '',
    from: '',
    showPay: false,
    showCheck: false,
    redirect: '/pages/goods_order/goods_order'
})
const orderInfo = reactive<any>({
    // 商品信息
    goods: [],
    // 地址信息
    address: {},
    // 订单类型（商品类型
    orderType: '0',
    // 配送方式
    deliveryTypeDesc: '快递配送',
    // 运费
    freightAmount: 0,
    // 优惠金额
    couponAmount: 0,
    // 商品总额
    goodsAmount: 0,
    // 实付金额
    orderAmount: 0
})
const orderParam = reactive<any>({
    buyType: 'buyNow',
    couponListId: '',
    buyGoods: {
        goodsId: '',
        skuId: '',
        num: '',
        cartId: ''
    },
    remark: '',
    addressId: 0,

    // 页面初始的参数
    param: null
})

watch(
    () => address,
    (value) => {
        orderParam.addressId = value.id
        orderInfo.address = value
    },
    { deep: true }
)

const getOrderDetail = async () => {
    try {
        const data = await orderSettle({ ...orderParam })
        Reflect.ownKeys(data).map((item: any) => {
            orderInfo[item] = data[item]
        })

        orderParam.addressId = data.address?.id
        unref(pageRef).close()
    } catch (error) {
        unref(pageRef)?.show({
            text: error,
            src: GoodsAbnormalImage
        })
        console.log('获取结算详情接口', error)
    }
}

const { isLock, lockFn: onSubmitOrder } = useLockFn(async () => {
    const modal: any = await uni.showModal({
        title: '温馨提示',
        content: '是否确认下单?',
        confirmColor: '#FF2C3C'
    })
    if (!modal.confirm) return
    try {
        const data = await orderSubmit({ ...orderParam })
        payState.orderId = data.orderId
        payState.from = PayFromType.ORDER
        payState.showPay = true
        payState.redirect =
            payState.redirect +
            `?buyGoods=${orderParam.param}&order_id=${data.orderId}&from=${PayFromType.ORDER}&checkPay=true`
        // payState.redirect =
        //     payState.redirect + `?&order_id=${data.orderId}&from=${PayFromType.ORDER}&checkPay=true`
    } catch (error) {
        console.log('创建订单', error)
    }
})

const handlePayResult = async () => {
    payState.showPay = false
    payState.showCheck = false
    const param = JSON.stringify({
        order_id: payState.orderId,
        from: payState.from
    })
    router.redirectTo({
        path: '/pages/payment_result/payment_result',
        query: {
            param: param
        }
    })
}

onLoad(async (options: any) => {
    await nextTick()
    console.log(options)
    try {
        if (!options.buyGoods) {
            throw new Error('参数有误')
        }
        Reflect.ownKeys(orderParam).map((item: any) => {
            if (!options[item]) return
            orderParam[item] = options[item]
        })
        orderParam.param = options.buyGoods
        console.log('data=>', options.buyGoods)

        orderParam.buyGoods = JSON.parse(options.buyGoods)

        await getOrderDetail()

        // h5支付用于弹起手动确认支付弹窗
        if (options?.checkPay) {
            payState.orderId = options.order_id
            payState.from = options.from
            payState.showCheck = true
            return
        }
    } catch (error) {
        unref(pageRef).show({
            text: error,
            src: GoodsAbnormalImage
        })
        console.log('订单结算', error)
    }
})
</script>

<style lang="scss" scoped>
page {
    height: 100%;
}

.goods-order {
    padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
}

.submit {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    height: calc(100rpx + env(safe-area-inset-bottom));
    padding: 0 24rpx env(safe-area-inset-bottom) 24rpx;

    &-btn {
        width: 220rpx;
        height: 74rpx;
        color: #ffffff;
        line-height: 74rpx;
        border-radius: 60px;
        background: linear-gradient(90deg, var(--theme-dark-color) 0%, var(--theme-color) 100%);
    }
}
</style>
